package com.digital.herbarium.Interceptor;


import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@Component
public class ZipSizeInterceptor implements HandlerInterceptor {
    // private static final int MAX_ZIP_SIZE = 20 * 1024 * 1024; // 20MB
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (MultipartFile file : fileMap.values()) {
                if (file.getSize() > Integer.parseInt(handler.toString())) {
                    // response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Zip file is too large");
                    return false;
                }
            }
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //可以实现后置处理器
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //可以实现完整处理器
    }


}
